# 为前端响应数据的PyeCharts类
import json

import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Grid, Bar, Map, Line, Pie
from pyecharts.charts import Timeline
from pyecharts.commons.utils import JsCode
from pyecharts.globals import ThemeType
from pyeCharts.pyeCharts import pyeCharts


class serverForPyeCharts:
    def __init__(self):
        pass

    # 获取各地区指定年份发展情况折线图数据
    @staticmethod
    def getDataForDevelopment(year):
        # 获取数据
        city_development_data = pd.read_excel('Excel\\各地区近10年发展指数.xlsx', index_col=0)
        year_list = city_development_data.columns.tolist()  # 获取年份列表
        index = city_development_data.index.tolist()  # 获取横坐标
        data_dict = {}
        x_data = index
        y_data = city_development_data[year].tolist()
        for i in range(len(index)):
            data_dict[index[i]] = y_data[i]
        data_dict = dict(sorted(data_dict.items(), key=lambda x: x[1], reverse=True))
        x_data = list(data_dict.keys())
        y_data = list(data_dict.values())
        c = (
            Bar(
                init_opts=opts.InitOpts(width="1600px", height="900px", theme=ThemeType.DARK)
            )
            .add_xaxis(x_data)
            .add_yaxis("发展指数", y_data, stack="stack1")
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
                title_opts=opts.TitleOpts(title=f"各地区{year}发展指数"),
                xaxis_opts=opts.AxisOpts(
                    axislabel_opts=opts.LabelOpts(rotate=45, interval=0)  # 设置标签旋转45度，并显示所有标签
                )
            )
        )
        return c

    # 获取各地区指定年份发展情况条形图数据 线性回归
    @staticmethod
    def getFutureDataForDevelopment(year):
        # 获取数据
        city_development_data = pd.read_excel('Excel\\各地区发展指数线性回归统计数据.xlsx', index_col=0)
        year_list = city_development_data.columns.tolist()  # 获取年份列表
        index = city_development_data.index.tolist()  # 获取横坐标
        data_dict = {}
        x_data = index
        y_data = city_development_data[year].tolist()
        for i in range(len(index)):
            data_dict[index[i]] = y_data[i]
        data_dict = dict(sorted(data_dict.items(), key=lambda x: x[1], reverse=True))
        x_data = list(data_dict.keys())
        y_data = list(data_dict.values())
        c = (
            Bar(
                init_opts=opts.InitOpts(width="1600px", height="900px", theme=ThemeType.DARK)
            )
            .add_xaxis(x_data)
            .add_yaxis("发展指数预测", y_data, stack="stack1")
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
                title_opts=opts.TitleOpts(title=f"各地区{year}发展指数"),
                xaxis_opts=opts.AxisOpts(
                    axislabel_opts=opts.LabelOpts(rotate=45, interval=0)  # 设置标签旋转45度，并显示所有标签
                )
            )
        )
        return c

    # 获取各地区指定年份发展情况地图数据
    @staticmethod
    def getDevelopmentMap(year):
        # 获取数据
        city_development_data = pd.read_excel('Excel\\各地区近10年发展指数.xlsx', index_col=0)
        data = pyeCharts().parsel_data(city_development_data)

        map_data = []
        for d in data:
            if d["time"] == year:
                temp_list = []
                for x in d["data"]:
                    temp_list.append([x["name"], x["value"]])
                map_data = temp_list
                break  # 只处理第一个匹配的年份

        data_list = []
        for t in [d[1][0] for d in map_data]:
            data_list.append(float(t))
        min_data, max_data = (
            min(data_list),
            max(data_list),
        )

        map_chart = (
            Map()
            .add(
                maptype="china",
                series_name="",
                data_pair=map_data,
                label_opts=opts.LabelOpts(is_show=True),
                is_map_symbol_show=False,
                itemstyle_opts={
                    "normal": {"areaColor": "#323c48", "borderColor": "#404a59"},
                    "emphasis": {
                        "label": {"show": Timeline},
                        "areaColor": "rgba(255,255,255, 0.5)",
                    },
                },
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(
                    title=f'各地区{year}年发展指数',
                    pos_left="center",
                    pos_top="top",
                    title_textstyle_opts=opts.TextStyleOpts(
                        font_size=25, color="rgba(255,255,255, 0.9)"
                    ),
                ),
                tooltip_opts=opts.TooltipOpts(
                    is_show=True,
                    formatter=JsCode(
                        """function(params) {
                        if ('value' in params.data) {
                            return params.data.value[2] + ': ' + params.data.value[0];
                        }
                    }"""
                    ),
                ),
                visualmap_opts=opts.VisualMapOpts(
                    is_calculable=True,
                    dimension=0,
                    pos_left="10",
                    pos_top="center",
                    range_text=["High", "Low"],
                    range_color=["lightskyblue", "yellow", "orangered"],
                    textstyle_opts=opts.TextStyleOpts(color="#ddd"),
                    min_=min_data,
                    max_=max_data,
                ),
            )
        )

        grid_chart = (
            Grid(init_opts=opts.InitOpts(width='1600px', height='900px'))
            .add(
                map_chart,
                grid_opts=opts.GridOpts(
                    pos_left="50%",
                    pos_right="10%",
                    pos_top="10%",
                    pos_bottom="10%"
                ),
                is_control_axis_index=True
            )
        )
        return grid_chart

    # 根据名称获取对应城市的线性回归预测图
    @staticmethod
    def drawLineForFutureGDP(city_name):
        # 获取数据
        city_ = []
        future_data = pd.read_excel('Excel\\各地区GDP(万亿元)线性回归统计数据.xlsx', index_col=0)
        city_.append(city_name)
        l = Line(
            init_opts=opts.InitOpts(
                width="1600px",
                height="900px",
                page_title="未来5年GDP线性回归预测图",
                renderer="canvas",
                theme="light",
            )
        )
        x_data = future_data.columns.tolist()
        l.add_xaxis(x_data)
        for city_index in future_data.index:
            if city_index in city_:
                y_data = future_data.loc[city_index].tolist()
                l.add_yaxis(city_index, y_data, linestyle_opts=opts.LineStyleOpts(width=2))
        l.set_global_opts(
            title_opts=opts.TitleOpts(title="未来5年GDP线性回归预测图.html", pos_left="center"),
            tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{a} <br/>{b} : {c}"),
            legend_opts=opts.LegendOpts(pos_left="left"),
            xaxis_opts=opts.AxisOpts(type_="category", name="x"),
            yaxis_opts=opts.AxisOpts(
                type_="log",
                name="y",
                splitline_opts=opts.SplitLineOpts(is_show=True),
                is_scale=True,
                # 设置刻度数量，这里是一个示例值，你可以根据需要调整
                split_number=10,
            ),
        )
        return l

    # 根据城市名和指标名获取指标折线图
    @staticmethod
    def drawLineForCity(city_name, indicator_name):
        # 读取对应指标下的数据
        filename = f'各地区近10年来{indicator_name}的变化'
        url = f'Excel\\{filename}.xlsx'
        city_common_data = pd.read_excel(url, index_col=0)

        city_name = [city_name]
        l = Line(
            init_opts=opts.InitOpts(
                width="1600px",
                height="900px",
                page_title=f"{filename}变化折线图",
                renderer="canvas",
                theme="light",

            )
        )
        x_data = city_common_data.columns.tolist()
        l.add_xaxis(x_data)
        for city_index in city_common_data.index:
            if city_index in city_name:
                y_data = city_common_data.loc[city_index].tolist()
                l.add_yaxis(city_index, y_data, linestyle_opts=opts.LineStyleOpts(width=2))
        l.set_global_opts(
            title_opts=opts.TitleOpts(title=f"{filename}", pos_left="center"),
            tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{a} <br/>{b} : {c}"),
            legend_opts=opts.LegendOpts(pos_left="left"),
            xaxis_opts=opts.AxisOpts(type_="category", name="x"),
            yaxis_opts=opts.AxisOpts(
                type_="log",
                name="y",
                splitline_opts=opts.SplitLineOpts(is_show=True),
                is_scale=True,
                # 设置刻度数量，这里是一个示例值，你可以根据需要调整
                split_number=10,
            ),
        )
        return l

    # 获取各项指标的权重
    @staticmethod
    def get_indicator_weight():
        weight_data = ['GDP', '地区人均可支配收入', '普通高等学校的数量', '医疗卫生机构的数量', '人均城市道路面积',
                       '城市用水普及率', '生活垃圾填埋量', '外贸进出口总额', '国内发明专利申请受理量']
        weights = [0.31, 0.19, 0.15, 0.1, 0.08, 0.06, 0.08, 0.02, 0.01]

        c = (
            Pie(init_opts=opts.InitOpts(bg_color="#2c343c", width="1600px", height="900px"))
            .add("", [list(z) for z in zip(weight_data, weights)])
            .set_global_opts(title_opts=opts.TitleOpts(title="各权重占比", pos_left="center",
                                                       pos_top="20",
                                                       title_textstyle_opts=opts.TextStyleOpts(color="#fff"), ),
                             legend_opts=opts.LegendOpts(is_show=False), )
            .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        )
        return c
